process.env.UV_THREADPOOL_SIZE = 128;
var port = 8008

var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var express = require('express');
var root = express();

root.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
//    res.header("Access-Control-Allow-Headers", "X-Requested-With");
//    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Methods","POST,GET");
//    res.header("X-Powered-By",' 3.2.1')
//    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

root.use(logger('dev'));
root.use(bodyParser.json({limit: '5mb'}));
root.use(bodyParser.urlencoded({limit: '5mb', extended: false}));

root.use(cookieParser());

//设置静态页面路径,路由路径由/client开始
root.use('/',express.static(path.join(__dirname, '/public')));

var https = require('https');
var pem = require('pem');
pem.createCertificate({days: 30, selfSigned: true}, function(err, keys) {
  console.error(err);
  var options = {
    key: keys.serviceKey,
    cert: keys.certificate
  };

    // Create an HTTPS service.
    var httpsServer = https.createServer(options, root).listen(port,function(err){
        if (err) {
            console.log(err)
            return
        }
        var uri = 'https://localhost:' + port
        console.log('Listening at ' + uri + '\n')

        // when env is testing, don't need open it
        if (process.env.NODE_ENV && process.env.NODE_ENV !== 'testing') {
            require('opn')(`https://localhost:${port}`)
        }
    });
    console.log(`serving on https://localhost:${port}`);

    root.set('http',httpsServer);
    var jfs = require('fs').readdirSync('./services');
    for(var i in jfs){
        try{
            if(/^.*?\.(js)$/.test(jfs[i]))
                require('./services/'+jfs[i]);
        }catch(e){
            console.error('express route ',jfs[i] + ':'+e);
        }    
    }
//    root.use('/*',express.static(path.join(__dirname,'/public')))
});

module.exports = root;

